package com.pricl.frame.core.web;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class WebBingdingInitializer implements WebBindingInitializer{
	
	private int autoGrowCollectionLimit;

	@Override
	public void initBinder(WebDataBinder binder, WebRequest request) {
		binder.setAutoGrowCollectionLimit(autoGrowCollectionLimit < 100 ? 1000 : autoGrowCollectionLimit);
		binder.registerCustomEditor(Date.class, new DateEditor());
		binder.registerCustomEditor(String.class, new StringEditor(true));
	}

	/**
	 * <p>
	 * 时间转换
	 * </p>
	 */
	private class DateEditor extends PropertyEditorSupport {

		private final SimpleDateFormat lsdfh = new SimpleDateFormat("yyyy-MM-dd HH");
		private final SimpleDateFormat lsdfhm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		private final SimpleDateFormat lsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		private final SimpleDateFormat ssdf = new SimpleDateFormat("yyyy-MM-dd");

		@Override
		public String getAsText() {
			Date value = (Date) getValue();
			if (value == null) {
				return "";
			}
			String text = lsdf.format(value);
			return text.replaceAll(" 00:00:00", "");
		}

		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			if (text == null || (text = text.trim()).isEmpty()) {
				setValue(null);
				return;
			}
			try {
				if (text.length() <= 10) {
					setValue(ssdf.parse(text));
				} else if (text.length() <= 13) {
					setValue(lsdfh.parse(text));
				} else if (text.length() <= 16) {
					setValue(lsdfhm.parse(text));
				} else if (text.length() <= 19) {
					setValue(lsdf.parse(text));
				} else {
					throw new IllegalArgumentException("不支持的时间格式");
				}
			} catch (ParseException e) {
				throw new IllegalArgumentException("不能转换成时间: " + e.getMessage(), e);
			}
		}

	}

	private class StringEditor extends PropertyEditorSupport {

		private final Boolean emptyAsNull;

		public StringEditor(Boolean emptyAsNull) {
			this.emptyAsNull = emptyAsNull;
		}

		@Override
		public void setAsText(String text) {
			if (text == null) {
				setValue(null);
				return;
			}
			if (this.emptyAsNull && text.isEmpty()) {
				setValue(null);
			} else {
				if (text.trim().isEmpty()) {
					setValue(text);
				} else {
					setValue(text.trim());
				}
			}
		}

		@Override
		public String getAsText() {
			Object value = getValue();
			return (value != null ? value.toString() : null);
		}

	}

	public int getAutoGrowCollectionLimit() {
		return autoGrowCollectionLimit;
	}

	public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) {
		this.autoGrowCollectionLimit = autoGrowCollectionLimit;
	}
}
